package com.ly.juc;

import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.*;

/**
 * @Classname TestThreadPool
 * @Description
 * 线程池的好处
 *
 * 1.txt.降低资源的消耗，创建和销毁损毁资源
 *
 * 2.提高响应的速度
 *
 * 3.方便管理
 *
 *
 *
 * 创建方式
 *
 * 1.txt. Executors  不推荐使用
 * 2. ThreadPoolExecutor 手动创建
 *
 *
 *
 * 7大参数
 *
 * corePoolSize 线程池核心线程大小
 *
 * maximumPoolSize 线程池最大线程数量
 *
 * keepAliveTime 空闲线程存活时间
 *
 * unit 空间线程存活时间单位
 *
 * workQueue 工作队列
 *
 * threadFactory 线程工厂
 *
 * handler 拒绝策略
 *
 *
 *
 * 4大拒绝策略
 *
 * 1.txt.CallerRunsPolicy 调用者线程中直接执行被拒绝任务的run方法，回到主线程调用
 *
 * 2.AbortPolicy  默认拒绝策略 直接丢弃，抛出异常
 *
 * 3.DiscardPolicy  直接丢弃，不抛出异常
 *
 * 4.DiscardOldestPolicy 丢弃队列最早的任务，尝试把这次拒绝的任务放入队列
 *
 *
 *
 * 最大线程数
 *
 * 1.txt.CPU密集型
 *
 * 最大线程池 = CPU内核*2 = 逻辑处理器个数
 *
 *
 *
 * 2.IO密集型
 * @Date 2020/10/4 19:32
 * @Author 冷心影翼
 */
public class TestThreadPool {

	public static void main(String[] args) {
//		createByExecutors();
//		createByThreadPoolExecutors();
		getCpu();
	}

	//不推荐使用
	public static void createByExecutors()  {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
		ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

		try{
			for(int i=0;i<10;i++) {
				fixedThreadPool.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}

			TimeUnit.SECONDS.sleep(2);
			System.out.println("-------");
			for(int i=0;i<10;i++) {
				singleThreadExecutor.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}

			TimeUnit.SECONDS.sleep(4);
			System.out.println("-------");
			for(int i=0;i<100;i++) {
				cachedThreadPool.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}
		}catch(Exception e){

		}finally {
			fixedThreadPool.shutdown();
			cachedThreadPool.shutdown();
			singleThreadExecutor.shutdown();
		}
	}

	public static void createByThreadPoolExecutors() {

		ExecutorService executorService =
			new ThreadPoolExecutor(4,8,3,
				TimeUnit.SECONDS,new LinkedBlockingQueue<>(10),
					Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
		try{
			for(int i=0;i<30;i++) {
				executorService.execute(()->{
					System.out.println(Thread.currentThread().getName());
				});
			}
		}catch(Exception e){
			System.out.println(e);
		}finally {
			executorService.shutdown();
		}


	}

	private static void getCpu() {
		System.out.println(Runtime.getRuntime().availableProcessors());
	}
}
